import axios from 'axios';
import dotenv from 'dotenv';
import { setTokenToStore, getTokenFromStore } from './tokenStore.js';

// 加载 .env 文件
dotenv.config();

// 定义请求的 URL
const url = `https://${process.env.IAMEndpoint}/v3/auth/tokens`;

// 定义请求的数据
const data = {
  auth: {
    identity: {
      methods: ['password'],
      password: {
        user: {
          name: process.env.IAMUserName,
          password: process.env.IAMPassword,
          domain: {
            name: process.env.IAMDomainId
          }
        }
      }
    },
    scope: {
      project: {
        name: process.env.IoTDA_REGION
      }
    }
  }
};

// 发送 POST 请求
async function fetchToken() {
  try {
    const response = await axios.post(url, data, {
      headers: {
        'Content-Type': 'application/json;charset=utf-8'
      }
    });
    // 从响应头中提取 X-Subject-Token
    const token = response.headers['x-subject-token'];
    if (!token) {
      throw new Error('X-Subject-Token not found in response headers');
    }
    console.log('Token:', token);
    setTokenToStore(token);
    return token;
  } catch (error) {
    console.error('Error fetching token:', error.response ? error.response.data : error.message);
    throw error;
  }
}

// 获取 Token 的函数
async function getToken() {
  const cachedToken = getTokenFromStore();
  if (cachedToken) {
    console.log('Using cached token');
    return cachedToken;
  }
  return fetchToken();
}

// 导出 getToken 函数
export { getToken };